package JasPerl::JSTL::Core::UrlTag;

use 5.010;
use strict;
use warnings;

use parent qw{
    JasPerl::TagExt::JspBodyTag
    JasPerl::JSTL::Core::ParamParent
};

use URI;

use JasPerl::PageContext;

sub set_context {
    JasPerl::JSTL::Core::UnsupportedAttributeException->throw('redirect', 'context');
}

sub set_scope {
    $_[0]->{scope} = JasPerl::PageContext->get_scope_by_name($_[1]);
}

sub set_value {
    $_[0]->{uri} = URI->new($_[1]);
}

sub set_var {
    $_[0]->{var} = $_[1];
}

sub do_tag {
    my $self = shift;
    JasPerl::JSTL::Core::NullAttributeException->throw('url', 'value')
        unless $self->{uri};
    $self->SUPER::do_tag();

    my $uri = $self->{uri};
    my $context = $self->get_jsp_context();
    # TODO: handle context attribute
    if (!$uri->scheme && $uri->path =~ m{^/}) {
        my $request = $context->get_request();
        $uri->path($request->get_context_path() . $uri->path)
    }

    my $url = "$uri";
    if (!$uri->scheme) {
        my $response = $context->get_response();
        $url = $response->encode_url($url);
    }

    if (defined $self->{var}) {
        $context->set_attribute($self->{var}, $url, $self->{scope});
    } else {
        $context->get_out()->print($url);
    }
}

1;
